/*******************************************************************************
 (c) 2005-2014 Copyright, Real-Time Innovations, Inc.  All rights reserved.
 RTI grants Licensee a license to use, modify, compile, and create derivative
 works of the Software.  Licensee has the right to distribute object form only
 for use with RTI products.  The Software is provided "as is", with no warranty
 of any type, including any warranty for fitness for any purpose. RTI is under
 no obligation to maintain or support the Software.  RTI shall not be liable for
 any incidental or consequential damages arising out of the use or inability to
 use the software.
 ******************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
/* keys_subscriber.cs

   A subscription example

   This file is derived from code automatically generated by the rtiddsgen 
   command:

   rtiddsgen -language C# -example <arch> keys.idl

   Example subscription of type keys automatically generated by 
   'rtiddsgen'. To test them, follow these steps:

   (1) Compile this file and the example publication.

   (2) Start the subscription with the command
       objs\<arch>\keys_subscriber <domain_id> <sample_count>

   (3) Start the publication with the command
       objs\<arch>\keys_publisher <domain_id> <sample_count>

   (4) [Optional] Specify the list of discovery initial peers and 
       multicast receive addresses via an environment variable or a file 
       (in the current working directory) called NDDS_DISCOVERY_PEERS. 

   You can run any number of publishers and subscribers programs, and can 
   add and remove them dynamically from the domain.
                                   
   Example:
        
       To run the example application on domain <domain_id>:
                          
       bin\<Debug|Release>\keys_publisher <domain_id> <sample_count>  
       bin\<Debug|Release>\keys_subscriber <domain_id> <sample_count>
              
       
modification history
------------ -------
*/

public class keysSubscriber
{

    public class keysListener : DDS.DataReaderListener
    {

        public override void on_requested_deadline_missed(
            DDS.DataReader reader,
            ref DDS.RequestedDeadlineMissedStatus status) { }

        public override void on_requested_incompatible_qos(
            DDS.DataReader reader,
            DDS.RequestedIncompatibleQosStatus status) { }

        public override void on_sample_rejected(
            DDS.DataReader reader,
            ref DDS.SampleRejectedStatus status) { }

        public override void on_liveliness_changed(
            DDS.DataReader reader,
            ref DDS.LivelinessChangedStatus status) { }

        public override void on_sample_lost(
            DDS.DataReader reader,
            ref DDS.SampleLostStatus status) { }

        public override void on_subscription_matched(
            DDS.DataReader reader,
            ref DDS.SubscriptionMatchedStatus status) { }

        /**** Start changes for Advanced_Keys ****/

        public override void on_data_available(DDS.DataReader reader)
        {
            keysDataReader keys_reader =
                (keysDataReader)reader;

            //// Start changes for Advanced_Keys

            while (true)
            {
                /* Given DDS_HANDLE_NIL as a parameter, take_next_instance returns
                a sequence containing samples from only the next (in a well-determined
                but unspecified order) un-taken instance.
                */

                try
                {
                    keys_reader.take_next_instance(
                        data_seq,
                        info_seq,
                        DDS.ResourceLimitsQosPolicy.LENGTH_UNLIMITED,
                        ref DDS.InstanceHandle_t.HANDLE_NIL,
                        DDS.SampleStateKind.ANY_SAMPLE_STATE,
                        DDS.ViewStateKind.ANY_VIEW_STATE,
                        DDS.InstanceStateKind.ANY_INSTANCE_STATE);
                }
                catch (DDS.Retcode_NoData)
                {
                    break;
                }
                catch (DDS.Exception e)
                {
                    Console.WriteLine("take error {0}", e);
                    return;
                }

                System.Int32 data_length = data_seq.length;
                /* We process all the obtained samples for a particular instance */
                for (int i = 0; i < data_length; ++i)
                {
                    /* We first check if the sample includes valid data */
                    if (info_seq.get_at(i).valid_data)
                    {
                        if (info_seq.get_at(i).view_state == DDS.ViewStateKind.NEW_VIEW_STATE)
                        {
                            new_instance_found(keys_reader, info_seq.get_at(i), data_seq.get_at(i));
                        }

                        /* We check if the obtained samples are associated to one
                        of the instances of interest.
                        Since take_next_instance gives sequences of the same instance,
                        we only need to test this for the first sample obtained.
                        */
                        if (i == 0 && !key_is_relevant(data_seq.get_at(i)))
                        {
                            break;
                        }

                        handle_data(keys_reader, info_seq.get_at(i), data_seq.get_at(i));
                    }
                    else
                    {
                        /* Since there is not valid data, it may include metadata */
                        keys dummy = null; ;

                        dummy = keysTypeSupport.create_data();
                        if (dummy == null)
                        {
                            throw new ApplicationException(
                            "keysTypeSupport.create_data error");
                        }

                        DDS.InstanceHandle_t handle = info_seq.get_at(i).instance_handle;

                        try
                        {
                            keys_reader.get_key_value(dummy, ref handle);
                        }
                        catch (DDS.Exception e)
                        {
                            Console.WriteLine(" get_key_value error {0}", e);
                        }

                        /* Here we print a message and change the instance state
                        if the instance state is ALIVE_NO_WRITERS or ALIVE_DISPOSED */
                        if (info_seq.get_at(i).instance_state == DDS.InstanceStateKind.NOT_ALIVE_NO_WRITERS_INSTANCE_STATE)
                        {
                            instance_lost_writers(keys_reader, info_seq.get_at(i), dummy);
                        }
                        else if (info_seq.get_at(i).instance_state == DDS.InstanceStateKind.NOT_ALIVE_DISPOSED_INSTANCE_STATE)
                        {
                            instance_disposed(keys_reader, info_seq.get_at(i), dummy);
                        }
                    }
                }

                try
                {
                    keys_reader.return_loan(data_seq, info_seq);
                }
                catch (DDS.Exception e)
                {
                    Console.WriteLine("return loan error {0}", e);
                }
            }
        }

        /* These are not called by DDS.   on_data_available() calls
        the appropriate function when it gets updates about
        an instances' status
        */
        public void new_instance_found(keysDataReader keys_reader,
                                       DDS.SampleInfo info,
                                       keys msg)
        {
            /* There are really three cases here:
               1.) truly new instance
               2.) instance lost all writers, but now we're getting data again
               3.) instance was disposed, but a new one has been created

               We distinguish these cases by examining generation counts, BUT
               note that if the instance resources have been reclaimed, the
               generation counts may be reset to 0.

               Instances are eligible for resource cleanup if there are no
               active writers and all samples have been taken.  To reliably
               determine which case a 'new' instance falls into, the application
               must store state information on a per-instance basis.

               Note that this example assumes that state changes only occur via
               explicit register_instance(), unregister_instance() and dispose()
               calls from the datawriter.  In reality, these changes could also
               occur due to lost liveliness or missed deadlines, so those
               listeners would also need to update the instance state.
             */

            switch (states[msg.code])
            {
                case Instance_State.inactive:
                    Console.WriteLine("New instance found; code = {0}", msg.code);
                    break;
                case Instance_State.active:
                    /* An active instance should never be interpreted as new */
                    Console.WriteLine("Error, 'new' already-active instance found; code = {0}", msg.code);
                    break;
                case Instance_State.no_writers:
                    Console.WriteLine("Found writer for instance; code = {0}", msg.code);
                    break;
                case Instance_State.disposed:
                    Console.WriteLine("Found reborn instance; code = {0}", msg.code);
                    break;
            }
            states[msg.code] = Instance_State.active;

        }

        public void instance_lost_writers(keysDataReader keys_reader,
                                          DDS.SampleInfo info,
                                          keys msg)
        {
            Console.WriteLine("Instance has no writers; code = {0}", msg.code);
            states[msg.code] = Instance_State.no_writers;
        }

        public void instance_disposed(keysDataReader keys_reader,
                                      DDS.SampleInfo info,
                                      keys msg)
        {
            Console.WriteLine("Instance disposed; code = {0}", msg.code);
            states[msg.code] = Instance_State.disposed;
        }

        /* Called to handle relevant data samples */
        public void handle_data(keysDataReader keys_reader,
                                DDS.SampleInfo info,
                                keys msg)
        {
            Console.WriteLine("code: {0}, x: {1}, y: {2}",
                               msg.code, msg.x, msg.y);
        }

        /* Called to determine if a key is relevant to this application */
        public bool key_is_relevant(keys msg)
        {
            /* For this example we just care about codes > 0,
               which are the ones related to instances ins1 and ins2 .*/
            return (msg.code > 0);
        }


        public keysListener()
        {
            data_seq = new keysSeq();
            info_seq = new DDS.SampleInfoSeq();

            /* Initialize instance states */
            states = new Instance_State[] {
                Instance_State.inactive,
                Instance_State.inactive,
                Instance_State.inactive};
        }

        /* Track instance state */
        protected enum Instance_State { inactive, active, no_writers, disposed };
        private Instance_State[] states;

        private keysSeq data_seq;
        private DDS.SampleInfoSeq info_seq;
    };
    /**** End changes for Advanced_Keys ****/

    public static void Main(string[] args)
    {

        // --- Get domain ID --- //
        int domain_id = 0;
        if (args.Length >= 1)
        {
            domain_id = Int32.Parse(args[0]);
        }

        // --- Get max loop count; 0 means infinite loop  --- //
        int sample_count = 0;
        if (args.Length >= 2)
        {
            sample_count = Int32.Parse(args[1]);
        }

        /* Uncomment this to turn on additional logging
        NDDS.ConfigLogger.get_instance().set_verbosity_by_category(
            NDDS.LogCategory.NDDS_CONFIG_LOG_CATEGORY_API, 
            NDDS.LogVerbosity.NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL);
        */

        // --- Run --- //
        try
        {
            keysSubscriber.subscribe(
                domain_id, sample_count);
        }
        catch (DDS.Exception)
        {
            Console.WriteLine("error in subscriber");
        }
    }

    static void subscribe(int domain_id, int sample_count)
    {

        // --- Create participant --- //

        /* To customize the participant QoS, use 
           the configuration file USER_QOS_PROFILES.xml */
        DDS.DomainParticipant participant =
            DDS.DomainParticipantFactory.get_instance().create_participant(
                domain_id,
                DDS.DomainParticipantFactory.PARTICIPANT_QOS_DEFAULT,
                null /* listener */,
                DDS.StatusMask.STATUS_MASK_NONE);
        if (participant == null)
        {
            shutdown(participant);
            throw new ApplicationException("create_participant error");
        }

        // --- Create subscriber --- //

        /* To customize the subscriber QoS, use 
           the configuration file USER_QOS_PROFILES.xml */
        DDS.Subscriber subscriber = participant.create_subscriber(
            DDS.DomainParticipant.SUBSCRIBER_QOS_DEFAULT,
            null /* listener */,
            DDS.StatusMask.STATUS_MASK_NONE);
        if (subscriber == null)
        {
            shutdown(participant);
            throw new ApplicationException("create_subscriber error");
        }

        // --- Create topic --- //

        /* Register the type before creating the topic */
        System.String type_name = keysTypeSupport.get_type_name();
        try
        {
            keysTypeSupport.register_type(
                participant, type_name);
        }
        catch (DDS.Exception e)
        {
            Console.WriteLine("register_type error {0}", e);
            shutdown(participant);
            throw e;
        }

        /* To customize the topic QoS, use 
           the configuration file USER_QOS_PROFILES.xml */
        DDS.Topic topic = participant.create_topic(
            "Example keys",
            type_name,
            DDS.DomainParticipant.TOPIC_QOS_DEFAULT,
            null /* listener */,
            DDS.StatusMask.STATUS_MASK_NONE);
        if (topic == null)
        {
            shutdown(participant);
            throw new ApplicationException("create_topic error");
        }

        // --- Create reader --- //

        /* Create a data reader listener */
        keysListener reader_listener =
            new keysListener();

        /* To customize the data reader QoS, use 
           the configuration file USER_QOS_PROFILES.xml */
        DDS.DataReader reader = subscriber.create_datareader(
            topic,
            DDS.Subscriber.DATAREADER_QOS_DEFAULT,
            reader_listener,
            DDS.StatusMask.STATUS_MASK_ALL);

        /* If you want to set the writer_data_lifecycle QoS settings
         * programmatically rather than using the XML, you will need to add
         * the following lines to your code and comment out the create_datareader
         * call above.
         */
        /*
        DDS.DataReaderQos readerQos = new DDS.DataReaderQos();
        subscriber.get_default_datareader_qos(readerQos);

        readerQos.ownership.kind = DDS.OwnershipQosPolicyKind.EXCLUSIVE_OWNERSHIP_QOS;

        DDS.DataReader reader = subscriber.create_datareader(
            topic,
            readerQos,
            reader_listener,
            DDS.StatusMask.STATUS_MASK_ALL);
         */

        if (reader == null)
        {
            shutdown(participant);
            reader_listener = null;
            throw new ApplicationException("create_datareader error");
        }

        // --- Wait for data --- //

        /* Main loop */
        const System.Int32 receive_period = 1000; // milliseconds
        for (int count = 0;
             (sample_count == 0) || (count < sample_count);
             ++count)
        {
            //Console.WriteLine("keys subscriber sleeping for {0} sec...",receive_period / 1000);

            System.Threading.Thread.Sleep(receive_period);
        }

        // --- Shutdown --- //

        /* Delete all entities */
        shutdown(participant);
        reader_listener = null;
    }


    static void shutdown(
        DDS.DomainParticipant participant)
    {

        /* Delete all entities */

        if (participant != null)
        {
            participant.delete_contained_entities();
            DDS.DomainParticipantFactory.get_instance().delete_participant(
                ref participant);
        }

        /* RTI Connext provides finalize_instance() method on
           domain participant factory for users who want to release memory
           used by the participant factory. Uncomment the following block of
           code for clean destruction of the singleton. */
        /*
        try {
            DDS.DomainParticipantFactory.finalize_instance();
        }
        catch(DDS.Exception e) {
            Console.WriteLine("finalize_instance error {0}", e);
            throw e;
        }
        */
    }
}


